import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/company_entity.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';

class SearchCompanyController extends GetxController {
  MultiState multiState = MultiState.success;
  List<String> historyRecordList = [];
  List<CompanyEntity> companyList = [];
  List<CompanyEntity> companySearchList = [];
  TextEditingController searchController = TextEditingController();
  String keyword = "";

  @override
  void onReady() {
    super.onReady();
    companyList = Get.arguments ?? [];
    getHistoryRecord();
  }

  @override
  void onClose() {
    SPUtils.saveStringList(SPUtils.SEARCH_COMPANY_HISTORY_RECORD, historyRecordList);
  }

  Future<void> getHistoryRecord() async {
    historyRecordList = await SPUtils.getStringList(SPUtils.SEARCH_COMPANY_HISTORY_RECORD);
    update();
  }

  void deleteHistoryRecord() {
    if (historyRecordList.isNotEmpty) {
      historyRecordList = [];
      SPUtils.saveStringList(SPUtils.SEARCH_COMPANY_HISTORY_RECORD, historyRecordList);
      update();
    }
  }

  void addHistoryRecord() {
    if (keyword.isEmpty) {
      return;
    }
    if (historyRecordList.contains(keyword)) {
      historyRecordList.remove(keyword);
    }
    if (historyRecordList.isEmpty) {
      historyRecordList.add(keyword);
    } else {
      if (historyRecordList.length >= 10) {
        historyRecordList.removeLast();
      }
      historyRecordList.insert(0, keyword);
    }
  }

  void searchCompany(String value) {
    keyword = value;
    companySearchList = [];
    if (keyword.isNotEmpty) {
      companyList.forEach((element) {
        String name = element.name ?? "";
        if (name.isNotEmpty && name.contains(keyword)) {
          companySearchList.add(element);
        }
      });
    }
    if (companySearchList.isNotEmpty) {
      multiState = MultiState.success;
      addHistoryRecord();
    } else {
      multiState = MultiState.empty;
    }
    update();
  }

  void backResult(String companyId, String companyName) {
    if (companyId.isEmpty) {
      ToastUtils.toast("公司id为空");
      return;
    }
    Get.back(result: {
      Constant.PARAM_COMPANY_ID: companyId,
      Constant.PARAM_COMPANY_NAME: companyName,
    });
  }
}
